//
//  LZMsgCenterCommentViewController.m
//  laziz_Merchant
//
//  Created by xbnzd on 17/3/14.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZMsgCenterCommentViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "IQKeyboardManager.h"
#import "LAReviewTableViewCell.h"
#import "LAReviewModel.h"
#import "LZMsgCenterPresenter.h"
#import "LZManageReviewsPresenter.h"
#import "LZReviewsReplyModel.h"
#import "LZUserModel.h"
#import "LZCustomerUserModel.h"

#import "extobjc.h"

@interface LZMsgCenterCommentViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,LAReviewCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)NSMutableArray *dataArr;
@property (nonatomic, strong) UITextField *textField;       // 用于占位的
@property (nonatomic, strong) UITextField *textInputReview; // 显示在键盘上的
@property (nonatomic, strong) UITextField *textTemp;        // 记录点击的textField

@property (nonatomic, assign) BOOL isShowKeyBoard;
@property (nonatomic, strong) LZMsgCenterPresenter *msgPresenter;
@property (nonatomic, strong) LZManageReviewsPresenter *manageReviewsPresenter;

@end

@implementation LZMsgCenterCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self configureUI];
    [self configReplyTextField];
    
    [self getDataAction];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self tapAction];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)dealloc {
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [center removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - UI & data
- (void)configureUI
{
    self.umLogPageViewName = @"中心 餐厅视频评论详情";
    self.title = LZLocalizedString(@"message_review_details", nil);
    
    self.dataArr = @[].mutableCopy;
    
    _msgPresenter = [[LZMsgCenterPresenter alloc] init];
    _manageReviewsPresenter = [[LZManageReviewsPresenter alloc] init];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"LAReviewTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}

- (void)getDataAction
{
    if (self.reviewType == ReviewType_Video) {
        [self getVideoCommentData];
    }else{
        [self getRestaurantCommentData];
    }
}

- (void)getRestaurantCommentData
{
    @weakify(self);
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    [self.msgPresenter getRestaurantCommentDetailWithCommentID:self.commentId Success:^(LAReviewModel *model) {
         @strongify(self);
         [self stopLoadingViewForView:self.view];
         
         [self.dataArr addObject:model];
         [self.tableView reloadData];
     } Failure:^(NSString *fail) {
         @strongify(self);
         [self stopLoadingViewForView:self.view];
     }];
}

/**
 获取视频评论
 */
- (void)getVideoCommentData
{
    @weakify(self);
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    [self.msgPresenter getVideoCommentDetailWithCommentID:self.commentId Success:^(LAReviewModel *model) {
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        [self.dataArr addObject:model];
        [self.tableView reloadData];
        
    } Failure:^(NSString *fail) {
        @strongify(self);
        [self stopLoadingViewForView:self.view];
    }];
}

#pragma mark - private
- (void)configReplyTextField {
    
    //    [IQKeyboardManager sharedManager].enable = NO;
    self.textInputReview = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.textInputReview.backgroundColor = [UIColor whiteColor];
    self.textInputReview.layer.borderWidth = 0.5;
    self.textInputReview.returnKeyType = UIReturnKeySend;
    self.textInputReview.delegate = self;
    self.textInputReview.layer.borderColor = UIColorFromRGB(0x999999, 1).CGColor;
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.textField.inputAccessoryView = self.textInputReview;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.backgroundColor = [UIColor redColor];
    self.textField.hidden = YES;
    self.textField.delegate = self;
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center  addObserver:self selector:@selector(keyboardDidShow)  name:UIKeyboardDidShowNotification  object:nil];
    [center addObserver:self selector:@selector(keyboardDidHide)  name:UIKeyboardWillHideNotification object:nil];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    tap.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tap];
}

- (void)keyboardDidShow
{
    [IQKeyboardManager sharedManager].enable = NO;
    if (self.textTemp == self.textField && !self.isShowKeyBoard) {
        if (self.textInputReview.isFirstResponder == YES) {
            return;
        }
        self.isShowKeyBoard = YES;
        [self.textInputReview becomeFirstResponder];
    }
}

- (void)keyboardDidHide
{
    self.isShowKeyBoard = NO;
    [IQKeyboardManager sharedManager].enable = YES;
}

#pragma mark - UITextFieldDelegate
- (void)tapAction
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    self.textTemp = textField;
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == self.textInputReview) {
        [self tapAction];

        LAReviewModel *m = self.dataArr[0];
       @weakify(self);
        if (self.reviewType == ReviewType_Video) {
            [self.manageReviewsPresenter replyReviewsWithMessageType:@"1" andReviewsUserId:m.customerUser.userId andCommentId:self.commentId andReplies:textField.text onSuccess:^(id data) {
                @strongify(self);
                if (m.replies == nil) {
                    m.replies = [NSMutableArray array];
                }
                [m.replies addObject:data];
                [self.tableView reloadData];
                
            } onFail:^(NSString *fail) {
                
            }];
        }else{
            [self.manageReviewsPresenter replyReviewsWithMessageType:@"2" andReviewsUserId:m.customerUser.userId andCommentId:self.commentId andReplies:textField.text onSuccess:^(id data) {
                @strongify(self);
                
                if (m.replies == nil) {
                    m.replies = [NSMutableArray array];
                }
                [m.replies addObject:data];
                [self.tableView reloadData];
                
            } onFail:^(NSString *fail) {
                
            }];

        }
    }
        DLog(@"发送发送发送");
    
    return YES;
}


#pragma mark - tablve deletage
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = [tableView fd_heightForCellWithIdentifier:@"cell" cacheByIndexPath:indexPath configuration:^(LAReviewTableViewCell *cell) {
        
        [cell getReviewLabel].numberOfLines = 0;
        
        [self configureCell:cell atIndexPath:indexPath];
    }];
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LAReviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    [self configureCell:cell atIndexPath:indexPath];
    
    return cell;
}

- (void)configureCell:(LAReviewTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
    
    cell.indexPath = indexPath;
    cell.textField = self.textField;
    cell.reviewType = self.reviewType;
    WS(weakSelf)
    cell.isShowKeyBoardStatus = ^BOOL(){
        return weakSelf.isShowKeyBoard;
    };
    
    cell.delegate = self;
    cell.reviewType = ReviewType_Restaurants;
    cell.headImageType = HeadImageType_User;
    
    cell.entity = self.dataArr[indexPath.section];
}

#pragma mark - cell deletate
-(void)refreshCellHeight:(NSIndexPath *)indexPath {
    [self.tableView reloadData];
}


- (void)deleteReplyWithIndex:(NSIndexPath*)indexPath
{
    LAReviewModel *m = self.dataArr[indexPath.section];
    LZReviewsReplyModel *replyM = m.replies.count > 0 ? m.replies[0] : nil;
    if (replyM) {
        @weakify(self);
        if (self.reviewType == ReviewType_Video) {
            [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
            [self.manageReviewsPresenter deleteReplyReviewsWithReplyId:replyM.replyId onSuccess:^(id data) {
                @strongify(self);
                [self stopLoadingViewForView:self.view];
                [m.replies removeAllObjects];
                m.replies = nil;
                [self.tableView reloadData];
                
            } onFail:^(NSString *fail) {
                @strongify(self);
                [self stopLoadingViewForView:self.view];
            }];
        }else{
            [self.manageReviewsPresenter deleteReplyReviewsWithReplyId:replyM.replyId onSuccess:^(id data) {
                @strongify(self);
                [self stopLoadingViewForView:self.view];
                [m.replies removeAllObjects];
                m.replies = nil;
                [self.tableView reloadData];
                
            } onFail:^(NSString *fail) {
                @strongify(self);
                [self stopLoadingViewForView:self.view];
            }];
        }
    }
    
}

@end
